package com.rrs.client.detail

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.google.gson.reflect.TypeToken
import com.rrs.client.MList
import com.rrs.client.R
import com.rrs.client.Response
import com.rrs.client.Utils
import com.rrs.client.databinding.ActivityPolicyDetailBinding
import com.rrs.client.entity.Policy
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request


class PolicyDetailActivity : AppCompatActivity() {

    private lateinit var binding: ActivityPolicyDetailBinding
    lateinit var utils: Utils
    val client = OkHttpClient()

    @SuppressLint("SetTextI18n", "ServiceCast")
    @OptIn(DelicateCoroutinesApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        utils = Utils(this)
        binding = ActivityPolicyDetailBinding.inflate(layoutInflater)


        val uri = intent.data
        var id = ""
        // 从网页跳转
        id = if (uri != null) {
            uri.getQueryParameter("id").toString()
        }
        // 从APP内跳转
        else {
            intent.getStringExtra("id").toString()

        }

        var res: Response<Policy>
        GlobalScope.launch(utils.globalScopeErrorHandler) {
            val type = object : TypeToken<MList<Policy>>() {}.type
            withContext(Dispatchers.IO) {
                res = utils.getObjsFromCloud<Policy>(
                    client,
                    "${resources.getString(R.string.ServerUrl)}/getPolicy?id=${id}",
                    type,
                    "policy-${id}",
                    false
                )
            }
            withContext(Dispatchers.Main) {
                val item = res.list[0]
                val type = Typeface.createFromAsset(
                    binding.title.context.assets,
                    "fonts/SourceHanSerifSC-Heavy.otf"
                )
                binding.title.typeface = type

                binding.title.text = item.title
                binding.content.text = item.content
                binding.info.text = "· ${item.pageview} 次浏览 ·"

                Glide.with(this@PolicyDetailActivity)
                    .load("${resources.getString(R.string.ServerUrl)}/getFile?name=${item.coverImg}&path=PolicyCover/")
                    .into(binding.img)
                setContentView(binding.root)
            }
            // 浏览量+1
            withContext(Dispatchers.IO) {
                Log.d("", "policyPageviewAdd1?id=${id}")
                val request: Request = Request.Builder()
                    .url("${resources.getString(R.string.ServerUrl)}/policyPageviewAdd1?id=${id}")
                    .post(FormBody.Builder().build())
                    .build()
                client.newCall(request).execute().use { res ->

                }
            }
        }

        binding.copyLink.setOnClickListener {
            val link = "http://shiyue0x0.top:9902/#/Policy/${id}"
            val clipData = ClipData.newPlainText("link", link)
            val clipboardManager =
                getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
            clipboardManager.setPrimaryClip(clipData)
            utils.sendMsg("复制成功，可以分享了")
        }
    }
}